/*
 * Copyright (c) 2012 Google Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */
package com.google.eclipse.protobuf.cdt.actions;

import static org.eclipse.xtext.util.Strings.isEmpty;

import java.io.*;
import java.util.regex.*;

import org.eclipse.cdt.core.model.*;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.core.runtime.*;
import org.eclipse.ui.IEditorPart;

import com.google.inject.Singleton;

/**
 * @author alruiz@google.com (Alex Ruiz)
 */
@SuppressWarnings("restriction")
@Singleton class ProtoFilePathFinder {
  private static final Pattern PROTO_PATH_PATTERN = Pattern.compile("// source: (.*)");

  IPath findProtoFilePathIn(IEditorPart editor) {
    CEditor cEditor = (CEditor) editor;
    String contents = contentsOf(cEditor);
    if (isEmpty(contents)) {
      return null;
    }
    String line = null;
    int lineCounter = 0;
    BufferedReader reader = new BufferedReader(new StringReader(contents));
    try {
      while ((line = reader.readLine()) != null) {
        switch (lineCounter) {
          case 0:
            if (!"// Generated by the protocol buffer compiler.  DO NOT EDIT!".equals(line)) {
              return null;
            }
            lineCounter++;
            break;
          case 1:
            return pathFrom(line);
        }
      }
    } catch (IOException e) {}
    return null;
  }

  private String contentsOf(CEditor cEditor) {
    ICElement input = cEditor.getInputCElement();
    if (input instanceof ITranslationUnit) {
      ITranslationUnit translationUnit = (ITranslationUnit) input;
      return new String(translationUnit.getContents());
    }
    return null;
  }

  private IPath pathFrom(String line) {
    Matcher matcher = PROTO_PATH_PATTERN.matcher(line);
    if (!matcher.matches()) {
      return null;
    }
    String path = matcher.group(1);
    return (!isEmpty(path)) ? new Path(path) : null;
  }
}
